package com.geen.tuoke.ui.activity

import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.core.view.isVisible
import com.blankj.utilcode.util.DeviceUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseActivity
import com.geen.tuoke.base.EmptyViewModel
import com.geen.tuoke.bean.WxFileInfo
import com.geen.tuoke.databinding.ActivityImportWxFileBinding
import com.geen.tuoke.databinding.ItemWxFileBinding
import com.geen.tuoke.ui.adapter.WxFileAdapter
import com.geen.tuoke.ui.dialog.DialogSure
import com.geen.tuoke.utils.ext.initClose
import com.geen.tuoke.utils.ext.toastShort
import kotlinx.android.synthetic.main.include_toolbar.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.lang.Exception

/**
 * @Author LuoJi
 * @Date 2022/1/18-16:26
 * @Desc 获取微信收到的excel文件
 * Android11 之前都是可以获取到App/data/package 下的目录
 * Android11 之后限制了访问，只能通过uri 方式单个文件选择访问
 */
class ImportWxFileActivity : BaseActivity<EmptyViewModel, ActivityImportWxFileBinding>() {

    lateinit var mAdapter: BaseQuickAdapter<WxFileInfo, BaseDataBindingHolder<ItemWxFileBinding>>
    private var listWxFiles = arrayListOf<WxFileInfo>()

    override fun getLayoutId(): Int {
        return R.layout.activity_import_wx_file
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(mBinding) {
            lifecycleOwner = this@ImportWxFileActivity

            viewImport.setOnClickListener {
                openWX()
            }
        }
        toolbar.initClose("微信文件导入") {
            finish()
        }
        mViewModel.launchUI {
            listWxFiles()
            mAdapter.setList(listWxFiles)
            // 获取到的文件是空，并且是Android11
            if (listWxFiles.isNullOrEmpty() && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                //显示打开微信导入
                mBinding.viewImport.isVisible = true
            }
        }

        initAdapter()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.let {
            val uri = it.data as Uri
            mViewModel.launchUI {
                val path = copyWxFile(uri)
                toastShort("拷贝成功" + path)
                mViewModel.uploadFile("xxxxx",path,uploadCallBack = {

                })
            }
        }
    }

    private fun initAdapter() {

        mAdapter = WxFileAdapter()
        mBinding.mRecycleView.adapter = mAdapter

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val file = mAdapter.getItem(position)
            DialogSure(this,"确定上传当前文件吗？",clickSure = {

            }).showDialog()
        }
    }

    private fun openWX() {
        try {
            val intent = Intent()
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.component = ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI")
            startActivity(intent)
        } catch (e: ActivityNotFoundException) {
        }
    }

    private suspend fun listWxFiles() {
        withContext(Dispatchers.IO) {
            val filePath = "/storage/emulated/0/Android/data/com.tencent.mm/MicroMsg/Download"
            val file = File(filePath)
            val fileList = file.listFiles()
            fileList?.let {
                it.filter {
                    it.name.endsWith("xlsx")
                }.forEach {
                    listWxFiles.add(WxFileInfo(it.name, it.absolutePath))
                }
            }
        }
    }

    private suspend fun copyWxFile(uri: Uri): String {
        var copyPath = ""
        withContext(Dispatchers.IO) {
            //文件拷贝
            val tempFilePath = getExternalFilesDir("myappdir")
            if (!tempFilePath!!.exists()) {
                tempFilePath.mkdir()
            }
            val oriFile = File(uri.path)
            val tempFile = File(tempFilePath, oriFile.name)
            if (!tempFile.exists()) {
                tempFile.createNewFile()
            }
            val fileInputStream = contentResolver.openInputStream(uri)
            var outputStream: OutputStream? = null
            try {
                outputStream = FileOutputStream(tempFile)
                val buffer = ByteArray(1024)
                var len = -1
                while (run { len = fileInputStream!!.read(buffer);len != -1 }) {
                    outputStream.write(buffer, 0, len)
                }
                copyPath = tempFile.absolutePath
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                try {
                    outputStream?.close()
                    fileInputStream!!.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return copyPath
    }
}